<template>
    <div class="cesium-select-box"></div>
</template>

<script setup lang="ts">
import { ShallowRef, onBeforeUnmount, onMounted, shallowRef, watch } from 'vue'
import { useContextViewer } from './hooks/useCesiumContext'
import { Drawer } from 'cesium-extends'
import { IDegreeWithHeight } from '@/types/position'

const viewerRef = useContextViewer()!

const drawerTool = shallowRef<Drawer>()

const emit = defineEmits<{
    'box-end': [positions: Cesium.Cartesian3[], lngLat: IDegreeWithHeight[]]
}>()

watch(
    viewerRef,
    (n) => {
        if (n) {
            drawerTool.value = new Drawer(n!, {
                tips: {
                    init: '开始框选',
                    start: '左键添加点，右键移除点，双击结束绘制',
                },
            })
        }
    },
    {
        immediate: true,
    },
)

// onMounted(() => {
//     console.log('box select mounted======>')

//     console.log('viewerRef?.value======>', viewerRef)

//     if (viewerRef?.value) {
//         debugger
//         // @ts-ignore 忽略警告
//     } else {
//         return console.warn('viewer not exsit')
//     }
// })

function handleBoxSelect() {
    console.log('start box ======>')

    drawerTool.value?.start({
        type: 'RECTANGLE',
        once: true,
        finalOptions: {
            // material: Cesium.Color.RED.withAlpha(0.8),
        },
        onEnd(entitys, positions) {
            if (viewerRef!.value) {
                const ellipsoid = viewerRef!.value?.scene.globe.ellipsoid

                const cartographicArray =
                    ellipsoid?.cartesianArrayToCartographicArray(positions)

                const lnglatArray = cartographicArray?.map((item) => ({
                    longitude: Cesium.Math.toDegrees(item.longitude),
                    latitude: Cesium.Math.toDegrees(item.latitude),
                    height: item.height,
                }))

                emit('box-end', positions, lnglatArray!)
            }
        },
    })
}

onBeforeUnmount(() => {
    drawerTool.value?.destroy()
    console.log('box select destroyed')
})

function handleBoxClear() {
    drawerTool.value?.reset()
}

defineExpose({
    handleBoxSelect,
    handleBoxClear,
})
</script>

<style lang="scss" scoped>
.cesium-select-box {
}
</style>
@/types/position